﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Microsoft.SharePoint.Client;

namespace SPUploader.Core
{
    public class SPService
    {
        #region Private Constants
        private const string DOCUMENT_LIBRARY = "DocumentLibrary";
        #endregion

        #region Properties
        public string SiteUrl { get; set; }
        public string DocumentLibrary { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Domain { get; set; }
        public bool UserCurrentUserCredentials { get; set; }
        #endregion

        #region Methods
        public List<string> DocumentLibraryList()
        {
            List<string> libraries = new List<string>();

            using (ClientContext clientcontext = new ClientContext(this.SiteUrl))
            {
                //Load Libraries from SharePoint     
                clientcontext.Load(clientcontext.Web.Lists);
                clientcontext.ExecuteQuery();
                foreach (List list in clientcontext.Web.Lists)
                {
                    try
                    {
                        if (list.BaseType.ToString() == DOCUMENT_LIBRARY)
                        {
                            // here u get all document library
                            libraries.Add(list.Title.ToString());
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return libraries;
        }

        public bool UploadFile(string filePath, ICredentials credential)
        {
            bool _result = false;

            if (System.IO.File.Exists(filePath))
            {
                using (ClientContext ctx = new ClientContext(this.SiteUrl))
                {
                    //if (this.UserCurrentUserCredentials)
                    //    ctx.Credentials = CredentialCache.DefaultNetworkCredentials;
                    //else
                    //    ctx.Credentials = new NetworkCredential(this.UserName, this.Password, this.Domain);
                    ctx.Credentials = credential;

                    var web = ctx.Web;
                    var fciNewFileFromComputer = new FileCreationInformation();

                    fciNewFileFromComputer.Content = System.IO.File.ReadAllBytes(string.Format(filePath));//openDialog.FileName);
                    fciNewFileFromComputer.Url = System.IO.Path.GetFileName(string.Format("{0}{1}", System.IO.Path.GetFileName(filePath), System.IO.Path.GetExtension(filePath)));//openDialog.FileName);

                    List docs = web.Lists.GetByTitle(this.DocumentLibrary);

                    Microsoft.SharePoint.Client.File uploadedFile = docs.RootFolder.Files.Add(fciNewFileFromComputer);
                    ListItem item = uploadedFile.ListItemAllFields;

                    item.Update();

                    Microsoft.SharePoint.Client.User sharepointUser = ctx.Web.CurrentUser;

                    try
                    {
                        item.Update();
                        ctx.Load(sharepointUser);
                        ctx.Load(uploadedFile);
                        ctx.ExecuteQuery();
                        item.Update();
                        //_logger.WriteToDatabase("Success", EventLogType.Success, _doc, "Sixco.SharePoint.DocumentsService.UploadDocument", fciNewFileFromComputer.Url.ToString());
                        _result = true;
                    }

                    catch (Exception ex)
                    {
                        //_logger.WriteToDatabase(ex.Message, EventLogType.Error, _doc, "Sixco.SharePoint.DocumentsService.UploadDocument", fciNewFileFromComputer.Url.ToString());
                    }
                }
            }

            else
            {
                //_logger.WriteToDatabase("File does not exsits any more", EventLogType.Error, _doc, "Sixco.SharePoint.UploadDocument", null);
            }
            return _result;
        }
        #endregion
    }
}
